package at.com.vn.chess.network;


import java.io.*;
import java.net.*;
import java.util.Properties;

public class ClientUtil {

	// Variable
	String result = "";
	URLConnection con = null;

	String name = "Mr X";
	String currentRoomID;
	URL context;
	String servlet;
	int chessTableID = 0;

	public ClientUtil(URL contx, String servletName, String userName,
			String roomID) {
		
		// Get parameter from web
		this.name = userName;
		this.currentRoomID = roomID;
		this.context = contx;
		this.servlet = servletName;
	}

	public ClientUtil(URL contx, String servletName, String userName,
			String roomID, int tableID) {
		
		// Get parameter from web
		this.name = userName;		
		this.context = contx;
		this.servlet = servletName;
		this.chessTableID = tableID;
		this.currentRoomID = roomID;
		
		if ((name == null) || name.equals("")) {
			name = "Mr. X";
			System.out.println(name);
		}
		if ((currentRoomID == null) || currentRoomID.equals("")) {
			currentRoomID = "room1";
			System.out.println(currentRoomID);
		}

	}

	public void sendBroadcastMessage(String xmlMessage) {
		try {
			URL url = new URL(context, servlet);
			HttpMessage msg = new HttpMessage(url);
			Properties props = new Properties();
			props.put("broadcast", xmlMessage);

			msg.sendPostMessage(props);
		} catch (SocketException e) {
			// Can't connect to host, report it and abandon the broadcast
			System.out.println( "Can't connect to host: " + e.getMessage());
		} catch (FileNotFoundException e) {
			// Servlet doesn't exist, report it and abandon the broadcast
			System.out.println( "sendBroadcastMessage-Resource not found: " + e.getMessage());
		} catch (Exception e) {
			// Some other problem, report it and abandon the broadcast
			System.out.println( "General exception: " + e.getClass().getName()
					+ ": " + e.getMessage());
		}
	}

	public String receiverMessage() {
		String nextMessage = null;
		while (nextMessage == null) {
			try {
				URL url = new URL(context, servlet);
				HttpMessage msg = new HttpMessage(url);
				InputStream in = msg.sendGetMessage();
				// DataInputStream data = new DataInputStream(
				// new BufferedInputStream(in));
				BufferedReader d = new BufferedReader(new InputStreamReader(in));

				nextMessage = d.readLine();

			} catch (SocketException e) {
				// Can't connect to host, report it and wait before trying again
				System.out.println( "Can't connect to host. Dang co gang de ket noi lai " );
				try {
					Thread.sleep(5000);
				} catch (InterruptedException ignored) {
					System.out.println( "Du doan: loi lien quan den thread" );
				}
			} catch (FileNotFoundException e) {
				// Servlet doesn't exist, report it and wait before trying again
				System.out.println( "receiverMessage-Resource not found: " + e.getMessage());
				try {
					Thread.sleep(5000);
				} catch (InterruptedException ignored) {
					System.out.println( "Du doan: loi lien quan den thread" );
				}
			} catch (Exception e) {
				// Some other problem, report it and wait before trying again
				System.out.println( "General exception: "
						+ e.getClass().getName() + ": " + e.getMessage());
				try {
					Thread.sleep(1000);
				} catch (InterruptedException ignored) {
					System.out.println( "Du doan: loi lien quan den thread" );
				}
			}
		}
		return nextMessage + "\n";
	}

	/**
	 * Get a connection to the servlet.
	 */
	private URLConnection getServletConnection() throws MalformedURLException,
			IOException {

		// Connection
		URL urlServlet = new URL(context, servlet);
		URLConnection con = urlServlet.openConnection();

		// konfigurieren
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false);
		con.setRequestProperty("Content-Type",
				"application/x-java-serialized-object");

		// und
		return con;
	}

	/**
	 * Send the inputField data to the servlet and show the result in the
	 * outputField.
	 */
	public String doPrivateData(String msgXML) {
		try {
			// send data to the servlet
			URLConnection con = getServletConnection();
			OutputStream outstream = con.getOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(outstream);
			oos.writeObject(msgXML);
			oos.flush();
			oos.close();

			// receive result from servlet
			InputStream instr = con.getInputStream();
			ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
			String result = (String) inputFromServlet.readObject();
			inputFromServlet.close();
			instr.close();

			// show result
			return result;

		} catch (Exception ex) {
			System.out.println( "Loi chua duoc xac dinh" );
		}
		return "";
	}
}